import express from 'express';
import errorMiddleware from './errorMiddleware';
import tokenMiddleware from './tokenMiddleware';
import userRouter from './api/user';
import loginRouter from './api/login';
import cors from 'cors';
import * as path from 'path';
import cookieParser from 'cookie-parser';
const app = express();   //创建一个express应用


const whiteList = ['http://localhost:3000'];
//加入cors中间件
app.use(cors({
  origin(origin: any, callback) {
    if (!origin) return callback(null, "*");
    if (whiteList.indexOf(origin) !== -1) callback(null, true);
    else callback(new Error('Not allowed by CORS'));
  },
  credentials: true
}));
//会在req对象中加入cookies属性，会在res对象中加入cookie方法，用于设置cookie
app.use(cookieParser());
//加入token中间件
app.use(tokenMiddleware);

const staticRoot = path.resolve(__dirname, '../../public');
app.use("/static", express.static(staticRoot))
//解析 application/x-www-form-urlencoded 格式的请求体
app.use(express.urlencoded({ extended: true }))
//解析json格式的请求体
app.use(express.json())

app.use("/api/user", userRouter);
app.use("/api/login", loginRouter);

app.use(errorMiddleware);
const port = 8888;
app.listen(port, () => {
  console.log(`server listen on ${port}`);

})